<template>
  <view class="page">
    <view class="top-buttons">
      <button class="top-button" @click="getConnectedWifi">当前WiFi</button>
      <button class="top-button" @click="getWifiList">周围WiFi</button>
    </view>

    <view class="connect-buttons">已连接：{{ connectedWifi.SSID }}</view>
    <view class="connect-buttons1">
      连接密码：<input style="margin-left: 80px;" v-model="password" placeholder="默认保存过的wifi" />
    </view>
    
    <view class="wifi-list-container">
      <view class="wifi-list">
        <view v-for="item in sortedWifiList" :key="item.BSSID" class="wifi-item" :class="{ 'robot': item.SSID === 'ROBOT' }">
          <text class="wifi-title">{{ item.SSID }}</text>
          <text class="wifi-signal">信号强度: {{ item.signalStrength }}</text>
          <button 
            class="btn connect-btn" 
            @click="connectWifi(item)"
            :disabled="item.SSID === connectedWifi.SSID">
            {{ item.SSID === connectedWifi.SSID ? '已连接' : '连接' }}
          </button>
        </view>
      </view>
    </view>

    <view class="ip-info">
      <view class="connect-buttons1">
        <text>当前地址:</text>
        <text>{{ serverIp }}</text>
      </view>
    </view>

    <view class="connect-buttons">
      <button @click="confirmNewIp1">跳转自动页</button>
      <button @click="confirmNewIp2">跳转手动页</button>
    </view>
	<text>端口：{{ sendport }}</text>
	  
	
	<view class="connect-buttons">
	<button class="button11" @click="portScan">扫描端口</button>
	<button  class="button11" @click="createWifi">开启wifi</button>
	</view>
	    <view class="port-scan-result">
	      <text>{{ portScanResult }}</text>
	    </view>
		
  </view>
</template>

<script>
  import { mapState, mapActions } from 'vuex';
  const FvvUniWifiHelper = uni.requireNativePlugin("Fvv-UniWifiHelper");
  import permision from "@/static/permission.js"; 

  export default {
    data() {
      return {
        wifiList: [], // 存储WiFi列表
        connectedWifi: { SSID: '当前未连接wifi' }, // 存储当前已连接wifi
        password: '', // 密码
        id: '', // 初始化 id
        currentWifi: '', // 当前WiFi名称
        nearbyWifiList: [], // 附近WiFi列表
        hasStartedWifi: false, // 标记是否已启动WiFi
        portScanResult: '', // 存储端口扫描结果
      };
    },
	onShow() {
	        // 每次页面显示时执行的逻辑
	        console.log('页面被显示');
	        
	        // 自动监听WiFi列表并连接名为“ROBOT”的WiFi
	        this.startWifiListening();
	    },

    computed: {
      ...mapState({
        serverIp: state => state.serverIp,
        sendport: state => state.sendport
      }),
      sortedWifiList() {
        // 将WiFi列表按信号强度排序
        return this.wifiList.sort((a, b) => b.signalStrength - a.signalStrength);
      }
    },
    onLoad(options) {
      if (options.id) {
        this.id = options.id;
      }
      if (options.currentWifi) {
        this.currentWifi = options.currentWifi;
      }
      this.init();
      
      this.getConnectedWifi();
      this.onWifiConnected();
      this.checkAndOpenWifi();
      this.getWifiList(); // 确保页面加载时获取WiFi列表
    },
    methods: {
      ...mapActions([
        'updateServerIp',
        'updateSendport'
      ]),
      /** 启动wifi */
      async getPermission(){
        var result = await permision.requestAndroidPermission("android.permission.ACCESS_FINE_LOCATION");
        var strStatus;
        if (result == 1) {
          strStatus = "已获得授权";
        } else if (result == 0) {
          strStatus = "未获得授权";
        } else {
          strStatus = "被永久拒绝权限";
        }
        uni.showModal({
          content: permisionID + strStatus,
          showCancel: false
        });
      },
      init(){
        FvvUniWifiHelper.init(res => {
          console.log(res); 
        });
        this.getPermission();
      },
	  startWifiListening() {
	              // 先检查并打开WiFi（如有必要）
				  
	              this.checkAndOpenWifi().then(() => {
	                  // 监听WiFi列表的变化
	                  this.onGetWifiList();
	                  // 触发获取WiFi列表
	                  this.getWifiList();
	              });
	          },

      async checkAndOpenWifi() {
					console.log("check"); 
                  const isWifiEnabled = await new Promise((resolve) => {
                      FvvUniWifiHelper.isWifiEnable(res => resolve(res));
                  });
      
                  console.log('WiFi开关状态:', isWifiEnabled);
      
                  if (!isWifiEnabled) {
                      console.log('WiFi未开启，尝试开启WiFi...');
                      FvvUniWifiHelper.openWifi();
                      await this.waitForWifiToEnable(); // 等待WiFi开启
                  }
              },
			   waitForWifiToEnable() {
			              return new Promise((resolve) => {
			                  const checkInterval = setInterval(() => {
			                      FvvUniWifiHelper.isWifiEnable(res => {
			                          if (res) {
			                              clearInterval(checkInterval);
			                              resolve(true);
			                          }
			                      });
			                  }, 1000); // 每秒检查一次
			              });
			          },
      createWifi(){ 
        FvvUniWifiHelper.openWifi();
      },
      closeAp(){
        FvvUniWifiHelper.closeWifiAp();
      },
      connectWifi1(){
        FvvUniWifiHelper.connectWifi({
          ssid: "ndyjy", 
        });
      }, 

      getLAN() {
        FvvUniWifiHelper.getLAN((res) => {
          const es = JSON.stringify(res, null, 2); // Declare 'es' with 'const'
          console.log(es); // Log the formatted JSON string
        });
      },
      portScan() {
        FvvUniWifiHelper.portScan({
          ip: this.serverIp,
          port: this.sendport,
          type: "udp"
        }, res => {
          console.log(res);
          if (res.type === 'result' && res.open) {
            this.portScanResult = `udp端口 ${res.port} 已开启`;
          } else if (res.type === 'finished') {
            if (!this.portScanResult) {
              this.portScanResult = '端口未开启';
            }
          }
        });
      },
      startWifi() {
        if (this.hasStartedWifi) {
          return Promise.resolve(true);
        }
        return new Promise((resolve, reject) => {
          uni.startWifi({
            success: (res) => {
              console.log('启动wifi 成功', res);
              this.hasStartedWifi = true;
              resolve(true);
            },
            fail: (err) => {
              console.error('启动wifi 失败', err);
              uni.showModal({
                content: err.errMsg,
                showCancel: false
              });
              reject(new Error(err));
            }
          });
        });
      },

      /** 获取wifi列表 */
      async getWifiList() {
        await this.startWifi();
        uni.getWifiList({
          success: (res1) => {
            console.log('获取wifi列表命令发送 成功', res1);
          },
          fail: (err) => {
            console.error('获取wifi列表 失败', err);
            uni.showModal({
              content: err.errMsg,
              showCancel: false
            });
          }
        });
        this.onGetWifiList(); // 监听WiFi列表
      },

      /** 监听获取wifi列表 */
      onGetWifiList() {
                  uni.onGetWifiList((res) => {
                      console.log('监听获取wifi列表', res);
                      const { wifiList } = res;
      
                      // 过滤同名WiFi信号
                      const filterList = wifiList.reduce((result, item) => {
                          const index = result.findIndex((v) => v.SSID === item.SSID);
                          if (index < 0) {
                              result.push(item);
                          } else if (item.signalStrength > result[index].signalStrength) {
                              result[index] = item;
                          }
                          return result;
                      }, []);
      

                      this.wifiList = filterList;
      
                      // 自动连接名为“ROBOT”的WiFi
                      const robotWifi = filterList.find(item => item.SSID === 'ROBOT');
                      if (robotWifi) {
                          console.log('找到ROBOT WiFi，自动连接...');
                          this.connectWifi(robotWifi);
                      }
                  });
              },

      /** 自动连接名为 "ROBOT" 的WiFi */
      autoConnectToRobotWifi() {
        const robotWifi = this.wifiList.find(wifi => wifi.SSID === 'ROBOT');
        if (robotWifi) {
          console.log('发现ROBOT WiFi，尝试自动连接...');
          this.connectWifi(robotWifi);
        } else {
          console.log('未发现ROBOT WiFi');
        }
      },

      /** 连接某个 Wi-Fi */
      connectWifi(wifi) {
        console.log('选中的wifi:', wifi);
        this.connectedWifi = { SSID: '' };
    
        // 使用 FvvUniWifiHelper 插件来连接 WiFi
        FvvUniWifiHelper.connectWifi({
          ssid: wifi.SSID,
          password: this.password,
          type: 'wpa' // 这里可以根据需要传入对应WiFi的密码
        }, (res) => {
          if (res.success) {
            console.log('wifi连接命令发送 成功:', res);
            uni.showToast({
              title: '连接成功',
              icon: 'success'
            });
            // 更新当前连接的WiFi信息
            this.getConnectedWifi();
          } else {
            console.error('wifi连接 失败:', res);
            uni.showModal({
              content: '连接失败，请手动连接',
              showCancel: false
            });
          }
        });
},

      /** 监听wifi连接状态 */
        onWifiConnected() {
              uni.onWifiConnected((res) => {
                console.log('监听wifi连接状态', res);
                this.connectedWifi = res.wifi;
                this.currentWifi = res.wifi.SSID; // 更新当前WiFi名称
              });
      },

      /** 获取当前连接的wifi */
      async getConnectedWifi() {
        this.connectedWifi = { SSID: '' };
        const hasStart = await this.startWifi();
        if (hasStart !== true) return;
        uni.getConnectedWifi({
          success: (res) => {
            console.log('获取当前连接的wifi 成功', res);
            this.connectedWifi = res.wifi; // 当前连接的wifi的信息
            this.currentWifi = res.wifi.SSID; // 更新当前WiFi名称
          },
          fail: (err) => {
            console.error('获取当前连接的wifi 失败:', err);
            uni.showModal({
              content: err.errMsg,
              showCancel: false
            });
          }
        });
      },

      confirmNewIp1() {
        if (this.newIp) {
          // 跳转到自动页面
          this.goToAutoPage();
        } else {
          uni.showToast({
            title: '请输入有效的IP地址',
            icon: 'none'
          });
        }
      },

      confirmNewIp2() {
        if (this.newIp) {
          // 跳转到手动页面
          this.goTomanual();
        } else {
          uni.showToast({
            title: '请输入有效的IP地址',
            icon: 'none'
          });
        }
      },

      goToAutoPage() {
        uni.navigateTo({
          url: `/pages/index/auto?id=${this.id}&newIp=${this.newIp}`
        });
      },

      goTomanual() {
        uni.navigateTo({
          url: `/pages/index/manual?id=${this.id}&newIp=${this.newIp}`
        });
      }
    }
  }
</script>


<style scoped>
.page {
  padding: 10px;
  font-family: Arial, sans-serif;
}
input {
  width: calc(80% - 20%);
  padding: 10px; /* 增加内边距以拉高输入框 */
  height: 40px; /* 或者直接设置高度 */
  border: 1px solid #ddd;
  border-radius: 5px;
}
.button11 {

  font-size: 12px; /* 调整字体大小 */
  width: 40px; /* 设置按钮宽度 */
  height: 50px; /* 设置按钮高度 */
  background-color: #007aff; /* 按钮背景色 */
  color: #ffffff; /* 按钮文字颜色 */
  border: none;
  border-radius: 5px;
  cursor: pointer;
}

.button11:active {
  background-color: #005bb5; /* 按下时按钮颜色 */
}
.top-buttons {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
}

.top-button {
  flex: 1;
  padding: 8px 5px;
  margin: 0 5px;
  font-size: 14px;
  background-color: #007aff;
  color: #ffffff;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  text-align: center;
}

.gc-box,
.info-item {
  flex: 1;
  margin-bottom: 15px;
  text-align: center;
}

.current-info,
.ip-info,
.connect-buttons {
  margin-top: 10px;
}
.connect-buttons1 {
  margin-top: 10px;
}

.wifi-list-container {
  max-height: 200px;
  overflow-y: auto;
  margin-top:-2px
}

.wifi-list {
  display: flex;
  flex-direction: column;
}

.wifi-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 3px 0;
  border-bottom: 1px solid #ddd;
  margin: 3px 0;
}
.wifi-item.robot {
  color: red;
}
.wifi-title {
  flex: 1;
  margin-right: 10px;
}

.wifi-signal {
  margin-right: 10px;
}

input {
  width: calc(100% - 20px);
  padding: 5px;
  border: 1px solid #ddd;
  border-radius: 5px;
}

button {
  padding: 8px 10px;
  font-size: 14px;
  background-color: #007aff;
  color: #ffffff;
  border: none;
  border-radius: 5px;
  cursor: pointer;
}

button:active {
  background-color: #005bb5;
}

.connect-buttons {
  display: flex;
  justify-content: space-between;
  margin-top: 10px;
}

.connect-buttons button {
  flex: 1;
  margin: 0 5px;
}

input[type="text"] {
  margin-top: 8px;
  padding: 5px;
  border: 1px solid #ddd;
  border-radius: 5px;
  width: 100%;
}

input[type="text"]:focus {
  outline: none;
  border-color: #007aff;
}

.new-ip {
  margin-top: 10px;
  text-align: left;
}
.port-scan-result {
  margin-top: 10px;
  font-size: 14px;
  color: #007aff;
  text-align: center;
}
</style>
